package util

import (
	"bytes"
	"encoding/binary"
	"fmt"
	"math"
	"strconv"
)

func Interface2String(inter interface{}) string {
	var str string
	switch inter.(type) {
	case string:
		str = inter.(string)
		break
	case int:
		str = strconv.Itoa(inter.(int))
		break
	case float64:
		str = strconv.FormatFloat(inter.(float64), 'E', -1, 64)
		break
	case []byte:
		str = string(inter.([]byte))
		break
	}

	return str
}

func Interface2Int(inter interface{}) int {
	var str int
	switch inter.(type) {
	case string:
		str, _ = strconv.Atoi(inter.(string))
		break
	case int:
		str = inter.(int)
		break
	case float64:
		str = int(inter.(float64))
		break
	case []byte:
		str = BytesToInt(inter.([]byte))
		break
	}

	return str
}

func Interface2Float64(inter interface{}) float64 {
	var str float64
	switch inter.(type) {
	case string:
		str, _ = strconv.ParseFloat(inter.(string), 64)
		break
	case int:
		str = float64(inter.(int))
		break
	case float64:
		str = inter.(float64)
		break
	case []byte:
		str = ByteToFloat64(inter.([]byte))
		break
	}

	return str
}

func BytesToInt(b []byte) int {
	bytesBuffer := bytes.NewBuffer(b)

	var x int32
	binary.Read(bytesBuffer, binary.BigEndian, &x)

	return int(x)
}

func ByteToFloat64(bytes []byte) float64 {
	bits := binary.LittleEndian.Uint64(bytes)
	return math.Float64frombits(bits)
}

func StrToInt(str string) int {
	if rint, err := strconv.Atoi(str); err != nil {
		panic(err)
	} else {
		return rint
	}
}

func StrToInt64(str string) int64 {
	if rint, err := strconv.ParseInt(str, 10, 64); err != nil {
		panic(err)
	} else {
		return rint
	}
}
func IntToStr(str int) string {
	return strconv.Itoa(str)
}

func Int64ToStr(num int64) string {
	return strconv.FormatInt(num, 10)
}

func FloatRound(f float64, n int) float64 {
	format := "%." + strconv.Itoa(n) + "f"
	res, _ := strconv.ParseFloat(fmt.Sprintf(format, f), 64)
	return res
}

func Float64ToStr(num float64) string {
	return strconv.FormatFloat(num, 'f', -1, 64)
}

func Float32ToStr(num float32) string {
	return strconv.FormatFloat(float64(num), 'f', -1, 32)
}
